package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.UserLocation;
import com.tanhua.domain.mongo.UserLocationDTO;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liuyp
 * @date 2021/02/05
 */
@Service
public class UserLocationApiImpl implements UserLocationApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void save(Long userId, Double longitude, Double latitude, String address) {
        //1. 查询userId是否有地址位置 数据
        Query query = new Query(Criteria.where("userId").is(userId));
        if (mongoTemplate.exists(query, UserLocation.class)) {
            //存在地理位置信息，要修改
            GeoJsonPoint point = new GeoJsonPoint(longitude, latitude);
            Update update = new Update()
                    .set("location", point)
                    .set("address", address)
                    .set("updated", System.currentTimeMillis());
            mongoTemplate.updateFirst(query, update, UserLocation.class);
        }else{
            //不存在，需要插入保存
            UserLocation userLocation = new UserLocation();
            userLocation.setId(ObjectId.get());
            userLocation.setUserId(userId);
            userLocation.setLocation(new GeoJsonPoint(longitude, latitude));
            userLocation.setAddress(address);
            userLocation.setCreated(System.currentTimeMillis());
            userLocation.setUpdated(System.currentTimeMillis());
            userLocation.setLastUpdated(System.currentTimeMillis());

            mongoTemplate.save(userLocation);
        }
    }

    @Override
    public List<UserLocationDTO> searchNear(Long userId, Integer metre) {
        //1. 查询得到用户自己的位置
        UserLocation userLocation = mongoTemplate.findOne(new Query(Criteria.where("userId").is(userId)), UserLocation.class);
        GeoJsonPoint point = userLocation.getLocation();

        //2. 以用户自己的位置为圆心，以metre范围为半径，划圆
        Distance distance = new Distance(metre/1000, Metrics.KILOMETERS);
        Circle circle = new Circle(point, distance);

        //3. 使用MongoDB搜索圆内的用户
        Query query = new Query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> userLocationList = mongoTemplate.find(query, UserLocation.class);

        //4. 转换成UserLocationDTO
        return UserLocationDTO.translateList(userLocationList);
    }
}
